<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="用工日期" prop="workTime">
        <el-date-picker
          v-model="queryParams.workTime"
          size="small"
          style="width: 200px"
          value-format="yyyy-MM-dd"
          type="date"
          range-separator="-"
          placeholder="选择日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

      <el-row :gutter="10" class="mb8">

        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['job:attendanceGroup:import']"
          >导入班组用工表</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['job:attendanceGroup:export']"
          >导出考勤模板</el-button>
        </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="attendanceInfoList"  >
      <el-table-column label="临时工考勤表" prop="orderCode" min-width="100"/>
      <el-table-column label="考勤日期" prop="workTime" :formatter="dateFormatter" width="100"/>
      <el-table-column label="班次" prop="timeShiftName" :show-overflow-tooltip="true" align="center" width="120"/>
      <el-table-column label="用工人数" prop="totalNum" :show-overflow-tooltip="true" align="center" width="120"/>
      <el-table-column label="考勤正常人数" prop="normalNum" :show-overflow-tooltip="true" align="center" width="120"/>
      <el-table-column label="勤异常人数" prop="abnormalNum" align="center" width="120">
        <template scope="scope">
          <span v-if="scope.row.abnormalNum!=0" style="color:#FF0000">{{ scope.row.abnormalNum }}</span>
          <span v-else >{{ scope.row.abnormalNum }}</span>
        </template>

      </el-table-column>
      <el-table-column label="考勤数据错误" prop="errorDataNum" align="center" width="120">
        <template scope="scope">
          <span v-if="scope.row.errorDataNum!=0" style="color:#FF0000">{{ scope.row.errorDataNum }}</span>
          <span v-else >{{ scope.row.errorDataNum }}</span>
        </template>

      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.status == 0">待确认</div>
          <div v-if="scope.row.status == 1">待处理</div>
          <div v-else-if="scope.row.status == 2">已经驳回</div>
          <div v-else-if="scope.row.status == 3">已确认</div>
          <div v-else-if="scope.row.status == 4">待审核</div>

        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['job:attendanceGroup:detail']"
          >详情
          </el-button>

          <el-button
            v-if=" scope.row.status==0 || scope.row.status ==2"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleStatus(scope.row)"
            v-hasPermi="['job:attendanceGroup:confirm']"
          >考勤确认
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleImg(scope.row)"
            v-hasPermi="['job:attendanceGroup:uploadPic']"
          >上传凭证
          </el-button>

          <el-button
            v-if="scope.row.picPath !=null"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handOpenImage(scope.row)"
            v-hasPermi="['job:attendanceGroup:viewPic']"
          >查看凭证
          </el-button>
          <el-button
            v-if="scope.row.picPath !=null"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handDelImage(scope.row)"
            v-hasPermi="['job:attendanceGroup:viewPic']"
          >删除凭证
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件</span>
        </div>

      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="uploadImg.title" :visible.sync="uploadImg.open" width="400px" append-to-body>
      <el-upload
        ref="uploadImg"
        :multiple="true"
        :limit="1000"
        accept=".jpg,.png"
        :headers="uploadImg.headers"
        :action="uploadImg.url"
        :disabled="uploadImg.isUploading"
        :on-progress="handleImgUploadProgress"
        :on-success="handleImgSuccess"
        :on-change="beforeUpload"
        :auto-upload="false"
        :file-list="fileList"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入.jpg,.png格式文件</span>
        </div>

      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="submitImgForm">确 定</el-button>
        <el-button @click="uploadImg.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div class="block">
        <span class="demonstration">查看凭证：</span>
        <el-image v-for="url in srcList" :key="url" :src="url" lazy>

          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline">loading...</i>
          </div>
        </el-image>

      </div>
      <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
            </span>
    </el-dialog>


  </div>
</template>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
<script>
import {listAttendanceInfo,changStatus,uploadPic,submitAudit} from "@/api/job/attendance/attendanceApi";
import { getToken } from "@/utils/auth";


export default {
  name: "attendanceInfo",
  created() {
    this.getList();

  },

  data() {
    return {
      statusOptions: [{value: 0, label: '数据异常'}, {value: 1, label: '待确认'}, {value: 2, label: '已确认'}],
      imgUrl: "",
      srcList: ["/images/loading/loading.gif"],
      fileList:[],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "工具类导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/workJobApi/attendance/importDataGroup",
        rowId:""
      },
      uploadImg: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "工具类导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,

        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url:process.env.VUE_APP_BASE_API + "/ploadPictureApi/addAttendanceImg" // 上传的图片服务器地址
      },
      dialogVisible:false,
      signUpLoading: true,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      attendanceInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      //提交审核表单
      auditWorkerParam: {
        processInstanceName: undefined,
        businessKey: undefined,
        processDefinitionKey: 'lsgkq',
        variables: undefined,
        processType: 2
      },
      //审核参数
      workerMap: {

        orderCode: undefined
      },
      signUp: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        //渠道名称
        groupName: undefined,
        //联系人
        workerName: undefined,
      },

      imgSrc:'',
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
    };
  },
      methods: {
        /**
         * 异常标记颜色
         * @param row
         * @param rowIndex
         * @returns {string}
         */
        tableRowClassName({row, rowIndex}) {
          if (row.status=== 0) {
            return 'warning-row';
          }
          return '';
        },
        /** 获取员工考勤信息列表 */
        getList() {
          this.loading = true;
          listAttendanceInfo(this.addDateRange(this.queryParams, this.dateRange)).then(
            response => {
              this.attendanceInfoList = response.rows;
              this.total = response.total;
              this.loading = false;
            }
          );
        },
        dateFormatter (row, column) {
          let datetime = row.workTime;
          if(datetime){
            datetime = new Date(datetime);
            let y = datetime.getFullYear() + '-';
            let mon = datetime.getMonth()+1 + '-';
            let d = datetime.getDate();
            return y + mon + d;
          }
          return ''
        },
        // 取消按钮
        cancel() {
          this.open = false;
          this.reset();
        },

        /** 搜索按钮操作 */
        handleQuery() {
          this.queryParams.pageNum = 1;
          this.getList();
        },

        /** 重置按钮操作 */
        resetQuery() {
          this.dateRange = [];
          this.resetForm("queryForm");
          this.handleQuery();
        },
        handleView(row) {
          var datetime =row.workTime;
          datetime = new Date(datetime);
          let y = datetime.getFullYear() + '-';
          let mon = datetime.getMonth()+1 + '-';
          let d = datetime.getDate();
         var workTime=  y + mon + d;
          this.$router.push({path:"/attendance/attendanceGroupDetail",query:{workTime:workTime,orderCode:row.orderCode}});
        },
        handleStatus(row) {
          var id =row.id;
          var errorDataNum =row.errorDataNum;
          var totalNum =row.totalNum;
          var normalNum =row.normalNum;
          if(errorDataNum >0){
            this.msgError("存在考勤数据错误状态，请先修改");
            return ;
          }
          let msg ="确认要确认吗?";
          if(totalNum <normalNum){
            msg="正常考勤人数多余需求用工人数，需要审核";
          }

          this.workerMap.orderCode = row.orderCode;
          this.auditWorkerParam.businessKey = row.id;
          let workTime =this.dateFormatter(row,0);
          this.auditWorkerParam.processInstanceName = workTime+ " 临时工考勤";
          this.auditWorkerParam.variables = this.workerMap;
          let auditWorkerParam= this.auditWorkerParam;
          this.$confirm(msg, "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {

            //用工需求人数少于正常考勤人数的时候 需要走审核流程
            if(totalNum <normalNum){
              submitAudit(auditWorkerParam).then(res => {
                this.loading = false;
                if (res.code === 200) {
                  this.msgSuccess(res.msg || '审核提交成功');

                  this.getList();
                } else {
                  this.msgError(res.msg || '审核提交错误');
                }
              })
            }else{
              //0 待确认 1 待处理  2 已经驳回 3  已确认
              return changStatus(id, 3);
            }

          }).then(() => {
            this.getList();
            this.msgSuccess(text + "成功");

          }).catch(function() {
            row.status = row.status === "0" ? "1" : "0";
          });
        },
        /** 下载模板操作 */
        handleExport() {
          var fileName ="_临时工考勤模板.xlsx";
          window.location.href = process.env.VUE_APP_BASE_API + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + false;
        },

        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
          this.getList();
        },
        // 图片上传中处理
        handleImgUploadProgress(event, file, fileList) {
          this.uploadImg.isUploading = true;
        },
        // 图片上传成功处理
        handleImgSuccess(response, file, fileList) {
          this.uploadImg.open = false;
          this.uploadImg.isUploading = false;
          this.$refs.uploadImg.clearFiles();
          this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
          this.getList();
        },
        beforeUpload(file,fileList) {
          // 1、判断文件名是否重复，不允许上传相同文件
          let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
          if(existFile){
            fileList.pop()
          }


          this.fileList = fileList;
        },
        // 提交上传文件
        submitFileForm() {
          this.$refs.upload.submit();
        },
        submitImgForm() {

          uploadPic(this.uploadImg.url,this.fileList).then(res => {
            this.getList();
            this.fileList = [];
            this.uploadImg.open = false;
            this.uploadImg.isUploading = false;
            this.$refs.uploadImg.clearFiles();

          });
        },

        /** 导入按钮操作 */
        handleImport() {
          this.upload.title = "导入班组用工表";
          this.upload.open = true;
        },

        /** 上传凭证按钮操作 */
        handleImg(row) {

          this.uploadImg.title = "上传凭证";
          this.uploadImg.open = true;
          this.uploadImg.url= "/ploadPictureApi/addAttendanceImg/" +row.id;
        },

        handOpenImage(row) {
          this.dialogVisible = true;
          var picPath=row.picPath;
          var array =picPath.split(";");

          this.srcList = array;

        },
        handDelImage(row) {
          var id =row.id;
          this.$router.push({path:"/attendance/attendanceGroupOptImg",query:{id:id}});
        },

      }
};
</script>
